package com.keray.web.push.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.keray.web.push.ClientData;
import com.keray.web.push.ClientMessageData;
import com.keray.web.push.WebSocket;
import com.keray.web.push.config.NameService;
import com.keray.web.push.config.NameServiceModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author by keray
 * date:2021/7/26 9:35 上午
 */
@RestController
@RequestMapping("/server/message")
@Slf4j
public class ServerApi {

    @Resource
    private WebSocket webSocket;

    @Resource
    private NameService nameService;


    @PostMapping("/push")
    public boolean sendUidMessage(@RequestBody ClientMessageData data) {
        List<NameServiceModel> services = nameService.allClient();
        return services.parallelStream().allMatch(v -> {
            try {
                String result = HttpUtil.post(StrUtil.format("http://{}:{}/web-push/server/message/notify", v.getIp(), v.getPort()), JSON.toJSONString(data));
                return Boolean.parseBoolean(result);
            } catch (Exception e) {
                return false;
            }
        });
    }


    @PostMapping("/notify")
    public boolean notifyMessage(@RequestBody ClientMessageData data) {
        ClientData clientData = clientMessage2ClientData(data);
        log.info("{}:发送通知：{}", nameService.owner().getIp(), data);
        if (data.isAsync()) {
            webSocket.asyncSend(data, clientData);
          return true;
        }
        return webSocket.syncSend(data, clientData).isEmpty();
    }

    private ClientData clientMessage2ClientData(ClientMessageData data) {
        ClientData clientData;
        if (data.getChannel() == 0) {
            clientData = new ClientData(data.getService(), null, data.getTargetId());
        } else if (data.getChannel() == 1) {
            clientData = new ClientData(data.getService(), data.getTargetId(), null);
        } else {
            clientData = new ClientData(data.getService(), null, null);
        }
        return clientData;
    }
}
